//
//  FANComposeView.m
//  Weibo - OC
//
//  Created by user on 16/4/25.
//  Copyright © 2016年 user. All rights reserved.
//

#import "FANComposeView.h"

//#warning 宏定义一定要放到 导入头文件的 上面, 会影响编译

//define this constant if you want to use Masonry without the 'mas_' prefix

#define MAS_SHORTHAND

//define this constant if you want to enable auto-boxing for default syntax

#define MAS_SHORTHAND_GLOBALS

#import <Masonry/Masonry.h>
#import "UIImage+ImageEffects.h"
#import "FANCompose.h"
#import "FANComposeButton.h"
#import <pop/POP.h>
#import "FANComposeViewController.h"

@interface FANComposeView ()

@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, strong) NSMutableArray *composeArray;

@property (nonatomic, strong) UIViewController *target;

@end

@implementation FANComposeView

- (NSMutableArray *)composeArray{
    
    if (!_composeArray) {
        
        _composeArray = [NSMutableArray array];
    }
    
    return _composeArray;
}

- (NSArray *)dataArray{
    
    if (!_dataArray) {
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"compose.plist" ofType:nil];
        
        NSArray *tempArray = [NSArray arrayWithContentsOfFile:path];
        
        NSMutableArray *mutable = [NSMutableArray arrayWithCapacity:tempArray.count];
        
        for (NSDictionary *dict in tempArray) {
            
            FANCompose *model = [FANCompose modelWithDict:dict];
            
            [mutable addObject:model];
        }
        
        _dataArray = mutable.copy;
        
    }
    
    return _dataArray;
}

- (UIImageView *)imageView{
    
    if (!_imageView) {
        
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"compose_slogan"]];
    }
    
    return _imageView;
}

- (void)show:(UIViewController *)target{
    
    [target.view addSubview:self];
    
    self.target = target;
    
}

- (instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        [self setupUI];
    }
    
    return self;
}

- (void)setupUI{
    
    self.backgroundColor = [UIColor cyanColor];
    
    self.frame = [UIScreen mainScreen].bounds;
    
    UIImage *image = [self getOriginalImage].applyLightEffect;
    
    UIImageView *backImageView = [[UIImageView alloc] initWithImage:image];
    
    [self addSubview:backImageView];
    
    [self addSubview:self.imageView];
    
    [self.imageView makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.equalTo(self.centerX);
        
        make.top.equalTo(self).offset(100);
        
    }];
    
    [self addComposeButton];
}

- (UIImage *)getOriginalImage{
    
    CGRect rect = [UIScreen mainScreen].bounds;
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    UIGraphicsBeginImageContextWithOptions(rect.size, true, 0);
    
    [window drawViewHierarchyInRect:rect afterScreenUpdates:false];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

- (void)addComposeButton{
    
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        CGFloat buttonW = 80;
        
        CGFloat buttonH = 110;
        
        CGFloat kMargin = ([UIScreen mainScreen].bounds.size.width - 3 * buttonW)/4;
        
        CGFloat rol = idx % 3;
        
        CGFloat row = idx / 3;
        
        FANCompose *model = (FANCompose *)obj;
        
        FANComposeButton *button = [[FANComposeButton alloc] initWithFrame:CGRectMake(0, 0, buttonW, buttonH)];
        
        [button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
        
        [button setImage:[UIImage imageNamed:model.icon] forState:UIControlStateNormal];
        
        [button setTitle:model.title forState:UIControlStateNormal];
        
        [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        
        CGRect rect1 = button.frame;
        
        rect1.origin.x = rol * buttonW + (rol + 1) * kMargin;
        
        button.frame = rect1;
        
        CGRect rect2 = button.frame;
        
        rect2.origin.y = row * buttonW + (row + 1) * kMargin + [UIScreen mainScreen].bounds.size.height ;
        
        button.frame = rect2;
        
        [self.composeArray addObject:button];
        
        [self addSubview:button];
    }];
    
}

- (void)didClickButton:(FANComposeButton *)button{
    
    [UIView animateWithDuration:0.25 animations:^{
        
        [self.composeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            FANComposeButton *comButton = (FANComposeButton *)obj;
            
            comButton.alpha = 0.01;
            
            if (comButton == button) {
                
                comButton.transform = CGAffineTransformMakeScale(2, 2);
                
            }else{
                
                comButton.transform = CGAffineTransformMakeScale(0.01, 0.01);
            }
            
        }];
        
    } completion:^(BOOL finished) {
        
        FANCompose *composeModel = self.dataArray[button.tag];
        
//        FANComposeViewController *comVc = [[FANComposeViewController alloc] init];
        
//        NSString *tempString = NSStringFromClass([FANComposeViewController class]);
        
//        NSLog(@"%@",tempString);
        
        Class classVc = NSClassFromString(composeModel.className);
        
        UIViewController *comVc = [classVc new];
        
//        UIViewController *comVc = (UIViewController *)classVc;
//        
//        comVc *Vc = [[comVc alloc] init];
        
        UINavigationController *nac = [[UINavigationController alloc] initWithRootViewController:comVc];
        
        [self.target presentViewController:nac animated:true completion:^{
        
            [self removeFromSuperview];
            
        }];
        
    }];
}

- (void)didMoveToSuperview{
    
    [super didMoveToSuperview];
    
    [self.composeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [self animation:obj and:idx and:true];
    }];
}

- (void)animation:(FANComposeButton *)obj and:(NSInteger)idx and:(BOOL)up{
    
    FANComposeButton *button = (FANComposeButton *)obj;
    
    POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPViewCenter];
    
    CGPoint changeP = CGPointMake(button.center.x, button.center.y + (up ? - 350 : 350));
    
    anim.toValue = [NSValue valueWithCGPoint:changeP];
    
    anim.springBounciness = 8;
    
    anim.springSpeed = 10;
    
    anim.beginTime = (double)idx*0.025 + CACurrentMediaTime();
    
    [button pop_addAnimation:anim forKey:@"haha"];
    
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [super touchesBegan:touches withEvent:event];
    
    for (int i = 0 ; i < self.composeArray.count/2; i++) {
        
        [self.composeArray exchangeObjectAtIndex:i withObjectAtIndex:self.composeArray.count - i - 1];
        
    }
    
    [self.composeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [self animation:obj and:idx and:false];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        
        [self removeFromSuperview];
        
    });
    
}

@end
